package script;

import java.util.ArrayList;

import main.Common;
import main.Def;

import convert.BaseContent;
import convert.EWorkBook;

public class Ex
{
	private BaseContent m_content;
	
	public Ex(String name)
	{
		m_content = getChild(name, EWorkBook.m_root);
	}
	
	public Ex(BaseContent bc)
	{
		m_content = bc;
	}
	
	public Ex get(String name)
	{
		return new Ex(getChild(name, m_content));
	}
	
	public String value()
	{
		if(m_content == null)
		{
			return "";
		}
		return m_content.getName();
	}
	
	public ArrayList<Ex> children()
	{
		if(m_content == null)
		{
			return null;
		}
		ArrayList<Ex> list = new ArrayList<>();
		int len = m_content.getChildNumber();
		for(int i = 0; i < len; ++i)
		{
			list.add(new Ex(m_content.getChildWithoutError(i)));
		}
		return list;
	}
	
	public String toString()
	{
		if(m_content != null)
		{
			return m_content.getName();
		}
		return "";
	}
	
	private BaseContent getChild(String text, BaseContent bc)
	{
		EString temp = new EString(text);
		ArrayList<EString> list = temp.split(Def.SPLIT_CHAR);
		for(EString es: list)
		{
			if(bc == null)
			{
				Common.print("content is null " + text);
				break;
			}
			int left = es.find(Def.INDEX_LEFT);
			int right = es.find(Def.INDEX_RIGHT, left + 1);
			String name = left < 0? es.toString(): es.toString(0, left);
			String index = es.toString(left + 1, right);
			int nameIndex = 0;
			Integer i = null;
			if(left > -1)
			{
				i = Common.isInt(index);
				if(i == null)
				{
					Common.print("name format wrong " + es.toString() + " of " + text);
					return null;
				}
				nameIndex = i;
			}
			if(!es.charAt(0).m_isTrans && (i = Common.isInt(name)) != null)
			{
				bc = bc.getChildWithoutError(i);
			}
			else 
			{
				bc = bc.getChildWithoutError(name, nameIndex);
			}
			if(bc == null)
			{
				Common.print("can't find name " + es.toString() + " of " + text);
				break;
			}
		}
		return bc;
	}
}
